<!--
 * @Author: wjk
 * @Date: 2020-01-09 16:06:59
 * @LastEditors: wjk
 * @LastEditTime: 2020-12-23 14:40:53
 * @description: 运费功能
 -->
<template>
  <view>
    <view v-if="token && comboShow" class="sLine addressArea">
      <view class="lCont">送至 </view>
      <view class="rCont" @click.stop="showPopup">
        <view v-if="!defaultAddress.province" class="addressInfo">请选择收货地区</view>
        <view v-else class="addressInfo">
          <block v-if="commodityType === 'bonusGift'">
            <view class="font-nowra-line2">{{ defaultAddress.province + defaultAddress.city + defaultAddress.area + defaultAddress.detail }}</view>
          </block>
          <block v-else-if="freightResult.freightIntervalDetails && freightResult.freightIntervalDetails.length">
            <view class="font-nowra" @click="showPopup">{{ defaultAddress.province + defaultAddress.city + defaultAddress.area + defaultAddress.detail }}</view>
            <view class="font-tip" @click.stop.prevent="showFreightRulePopup">查看运费规则></view>
          </block>
          <block v-else>
            <view class="font-nowra">{{ defaultAddress.province + defaultAddress.city + defaultAddress.area + defaultAddress.detail }}</view>
            <view v-if="isSend > 0" class="font-tip">{{ freightResult.freight > 0 ? freightResult.msg : '快递包邮' }}</view>
            <view v-else-if="isSend==0" class="font-tip">该地区暂不支持配送</view>
            <view v-else class="font-tip">{{ freightResult.msg }}</view>
          </block>
        </view>
        <image class="right_arror" src="/static/images/icon/icon_arror_right.png" />
      </view>
    </view>
    <base-popup :show="pShow" :show-close="false" @close="closePopup">
      <section class="maskContainer addressMask" @click.stop="" @touchmove.prevent>
        <view class="cartClose" @click="closePopup">
          <image src="/static/images/icon/icon_close.png" />
        </view>
        <view class="serviceContainer">
          <view class="title">配送至</view>
          <base-list-view
            :top="20"
            :fixed="false"
            height="720"
            class-name="address-list-box"
            :load-after-init="false"
            :enable-pull-refresh="false"
            @onPullRefresh="onPullRefresh"
            @onLoadMore="onLoadMore">
            <view class="address-list">
              <view v-for="(item, index) in freightAddress" :key="index" class="li" @click.stop.prevent="handleChoiceArea(item)">
                <span v-if="defaultAddress.address_id == item.address_id" class="item-choice item-checked"></span>
                <span v-else class="item-choice item-nochecked"></span>
                <view class="item-detail">
                  {{ item.province + item.city + item.area + item.detail }}
                </view>
              </view>
            </view>
          </base-list-view>
        </view>
        <view class="maskBottomBtn" @click="selectAddress">
          其他地区
        </view>
      </section>
    </base-popup>
    <base-popup :show="fShow" :show-close="false" @close="closePopup">
      <section class="maskContainer addressMask" @click.stop="" @touchmove.prevent>
        <view class="cartClose" @click="closePopup">
          <image src="/static/images/icon/icon_close.png" />
        </view>
        <view class="serviceContainer">
          <view class="title">运费规则</view>
          <scroll-view class="fright-rule-box" scroll-y>
            <view class="freight-rule-item">
              <view class="rule-item grey">商品数量区间</view>
              <view class="rule-item grey">首件邮费</view>
              <view class="rule-item grey">续件邮费</view>
            </view>
            <view v-for="(item, index) in freightResult.freightIntervalDetails" :key="index" class="freight-rule-item">
              <view class="rule-item">{{ item.goodsNumberRange }}</view>
              <view class="rule-item">{{ item.firstFeeStr }}</view>
              <view class="rule-item">{{ item.continuationFeeStr }}</view>
            </view>
          </scroll-view>
        </view>
        <view class="maskBottomBtn" @click="closePopup">
          我知道了
        </view>
      </section>
    </base-popup>
    <w-picker
      ref="selfChoiceAddr"
      mode="region"
      @confirm="handleAreaBtn"
    />
  </view>
</template>
<script>
import BaseListView from '@/components/base/base-listview'
import wPicker from '../w-picker/w-picker.vue'
// import wPicker from '@/pagesMine/address/w-picker/w-picker.vue'
import { mapState } from 'vuex'
export default {
  name: 'CommoditySend',
  components: {
    BaseListView,
    wPicker
  },
  props: {
    allData: {
      type: Object,
      default() {
        return {}
      }
    },
    commodityType: {
      type: String,
      default: 'single'
    }
  },
  data() {
    return {
      pShow: false,
      fShow: false, // 运费规则弹窗显示
      setNewId: '',
      addresstxt: '',
      allUnsupportedList: [],
      freightResult: {},
      adrrefreshing: false, // 地址是否刷新中
      adrloading: false, // 地址加载
      freightAddress: [], // 配送地址
      selfChoiceAddr: [], // 自己选择的地址
      defaultAddress: {},
      pageSize: 10, // 地址
      pageNo: 1,
      nomore: false,
      isSend: true, // 是否配送
      once: false,
      newTempId: ''
    }
  },
  computed: {
    ...mapState([
      'token',
      'userInfo'
    ]),
    comboShow() {
      let res = true
      if (this.allData.goods && this.allData.goods.type === 4 && !this.newTempId) {
        res = false
      } else if (this.once) {
        res = true
      }
      return res
    }
  },
  created() {
    this.getAddressList()
  },
  methods: {
    // 初始化数据
    initData() {
      this.pageNo = 1
      this.nomore = false
    },
    selectAddress() {
      this.closePopup()
      this.$refs['selfChoiceAddr'].show()
    },
    closePopup() {
      this.$set(this, 'pShow', false)
      this.$set(this, 'fShow', false)
    },
    showPopup() {
      this.pShow = true
    },
    showFreightRulePopup() {
      this.fShow = true
    },
    handleAreaBtn(state) {
      // 确认按钮
      if (state) {
        const areaArr = state.checkArr
        this.defaultAddress.province = areaArr[0]
        this.defaultAddress.city = areaArr[1]
        this.defaultAddress.area = areaArr[2]
        this.defaultAddress.address_id = ''
        this.defaultAddress.detail = ''
        this.defaultAddress.region_code = ''
        this.defaultAddress.is_default = 0
        this.handleChoiceArea(this.defaultAddress)
      }
    },
    // 选择地址
    handleChoiceArea(info) {
      this.defaultAddress = JSON.parse(JSON.stringify(info))
      if (this.defaultAddress.province) {
        this.getCalculateArea()
      }
      this.closePopup()
    },
    // 获取地址列表
    async getAddressList(val) {
      if (val) {
        this.once = true
        this.newTempId = val
      }
      if (!this.token) {
        return
      }
      const params = {
        pageSize: this.pageSize, // 地址
        pageNo: this.pageNo,
        hideLoading: true
      }
      const res = await this.$api.mineApi.getShippingAddressList(params)
      if (res.code) {
        return
      }
      this.freightAddress = res.data
      if (this.freightAddress.length === 1) {
        this.defaultAddress = JSON.parse(JSON.stringify(this.freightAddress[0]))
      } else {
        // const defaultArr = this.freightAddress.filter(item => item.is_default)
        const defaultArr = this.freightAddress
        let hasDefault = false
        if (defaultArr.length > 0) {
          defaultArr.filter((item, index) => {
            if (item.is_default === 1) {
              hasDefault = true
              this.defaultAddress = JSON.parse(JSON.stringify(this.freightAddress[index]))
            }
          })
          // 如果地址列表没有一个默认地址
          if (!hasDefault) {
            this.defaultAddress = JSON.parse(JSON.stringify(this.freightAddress[0]))
          }
          // console.log('this.defaultAddress', this.defaultAddress)
        } else {
          this.defaultAddress = {}
        }
      }
      if (this.defaultAddress.province) {
        this.getCalculateArea(val)
      }
    },
    // 下拉刷新
    async onPullRefresh(mescroll) {
      this.initData()
      this.commonData(mescroll)
    },
    // 上拉加载
    async onLoadMore(mescroll) {
      if (!this.mescroll) this.mescroll = mescroll
      if (this.nomore) {
        mescroll.endSuccess(0)
        return
      }
      this.pageNo = mescroll.num
      this.commonData(mescroll)
    },
    async commonData(mescroll) {
      const res = await await this.$api.mineApi.getShippingAddressList({
        pageSize: this.pageSize,
        pageNo: this.pageNo
      })
      if (res.success) {
        if (this.pageNo === 1) {
          this.freightAddress = []
        }
        this.freightAddress = this.freightAddress.concat(res.data)
        if (res.data.length < this.pageSize) {
          this.nomore = true
        }
        mescroll.endSuccess(this.pageSize)
      } else {
        this.freightAddress = []
        mescroll.endErr()
      }
    },
    // 获取运费信息
    async getCalculateArea(val) {
      if (!this.token) return
      let templateId = -1
      if (this.commodityType === 'boxGoods' || this.commodityType === 'bonusGift' || this.commodityType === 'bonusCloud') {
        templateId = this.allData.freight_template_id || 0
      } else {
        const template_id = (val || this.allData.goods.freight_template_id)
        templateId = template_id || -1
      }
      // 一般情况单个商品的 freight_template_id 不会改变，除非以下情况：组合套餐
      // 如果是外部设置
      if (val) {
        templateId = val
      } else if (!val && this.selectId) {
        // 如果外部没有重新设置id，但是内部已经有设置过一次
        templateId = this.selectId
      }
      this.selectId = templateId
      const params = [
        {
          'deliveryArea': this.defaultAddress.province,
          'deliveryAreaCode': '',
          'key': '',
          'quantity': 0,
          'calValue': 1,
          'templateId': templateId
        }
      ]
      const res = await this.$api.goodsApi.getCalculate(JSON.stringify(params))
      if (!res.code) {
        this.allUnsupportedList = res.data.allUnsupported
        this.freightResult = res.data.resultList[0]

        // 在配送地区
        if (this.freightResult.supported) {
          this.isSend = this.freightResult.supported
        } else {
          // 不在不配送地区
          this.isSend = this.freightResult.supported
        }
      }
      this.$emit('validProps', {
        type: 'isSend',
        isSend: !!this.isSend,
        defaultAddress: this.defaultAddress
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.addressArea {
  height: auto;
  overflow: hidden;
  .lCont{
    min-width: 52rpx;
  }
  .rCont{
    max-width: 100%;
  }
  .addressInfo {
    width: 100%;
    font-size: 13px;
    .font-nowra {
      @include no-wrap;
      width: 90%;
    }
    .font-nowra-line2{
      width: 90%;
      @include text-ellipsis-line;
    }
    .font-tip {
      margin-right: 20px;
      color: $color-price;
    }

  }
}
.addressMask {
  height: 900rpx;
  .serviceContainer {
    height: 720rpx;
    overflow: hidden;
    .title{
      font-weight: bold;
      line-height: 50rpx;
      font-size: 34rpx;
    }
    .fright-rule-box{
      height: 680rpx;
      margin-top: 20rpx;
      .freight-rule-item{
        display: flex;
        align-items: center;
        margin-bottom: 32rpx;
        justify-content: space-between;
        .rule-item{
          flex: 1;
          font-size: 28rpx;
          color: #000;
          &.grey{
            color: #999999;
          }
          &:nth-child(1){
            text-align: left;
          }
          &:nth-child(2){
            text-align: center;
          }
          &:nth-child(3){
            text-align: right;
          }
        }
      }
    }
  }
}
.address-list-box{
  height: 680rpx;
}
.address-list {
  .li {
    padding: 10px 0;
    display: flex;
    flex-direction: row;
    .item-choice {
      width: 17px;
      height: 17px;
      border-radius: 50%;
      margin-top: 2px;
    }
    .item-detail {
      flex: 1;
      font-size: 13px;
      padding-left: 10px;
    }
    .item-checked {
      background: url("~@/static/images/cart/icon_marquee_selected.png") no-repeat;
      background-size: 100%;
    }
    .item-nochecked {
      border: 1px solid #ccc;
    }
  }
}
</style>
